// SPDX-License-Identifier: GPL-2.0-only
/*
 * Copyright (C) 2005,2006,2007,2008 IBM Corporation
 *
 * Authors:
 * Kylene Hall <kjhall@us.ibm.com>
 * Reiner Sailer <sailer@us.ibm.com>
 * Mimi Zohar <zohar@us.ibm.com>
 *
 * File: ima_fs.c
 *	implemenents security file system for reporting
 *	current measurement list and IMA statistics
 */

#include <linux/fcntl.h>
#include <linux/kernel_read_file.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/seq_file.h>
#include <linux/rculist.h>
#include <linux/rcupdate.h>
#include <linux/parser.h>
#include <linux/vmalloc.h>

#include "ima.h"
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
#include "rtos_ima_digest_list.h"
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */

#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
#include <linux/crl_revocate.h>
#endif
#ifdef CONFIG_RTOS_IMA_MEASURE_THRESHOLD
#include "rtos_ima_measure_threshold.h"
#endif
#ifdef CONFIG_RTOS_IMA_TPM_DECOUPLE
#include "rtos_ima_tpm_decouple.h"
#endif

#ifdef CONFIG_RTOS_IMA_APPRAISE_FAILLOG
#include "rtos_ima_appraise_faillog.h"
#endif

#ifdef CONFIG_RTOS_IMA_ENHANCEMENT
#include "rtos_ima_enhancement.h"
#endif

/* max size of digest data without signature = 8M */
#define MAX_DIGEST_LEN (8 * 1024 * 1024)
/* max size of digest data signature = 1M */
#define MAX_DIGEST_SIG_LEN (1 * 1024 * 1024)

static DEFINE_MUTEX(ima_write_mutex);

#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
static DEFINE_MUTEX(digest_list_sig_enable_mutex);
#endif

bool ima_canonical_fmt;

static int __init default_canonical_fmt_setup(char *str)
{
#ifdef __BIG_ENDIAN
	ima_canonical_fmt = true;
#endif
	return 1;
}
__setup("ima_canonical_fmt", default_canonical_fmt_setup);

static int valid_policy = 1;

static ssize_t ima_show_htable_value(char __user *buf, size_t count,
				     loff_t *ppos, atomic_long_t *val)
{
	char tmpbuf[32];	/* greater than largest 'long' string value */
	ssize_t len;

	len = scnprintf(tmpbuf, sizeof(tmpbuf), "%li\n", atomic_long_read(val));
	return simple_read_from_buffer(buf, count, ppos, tmpbuf, len);
}

static ssize_t ima_show_htable_violations(struct file *filp,
					  char __user *buf,
					  size_t count, loff_t *ppos)
{
	return ima_show_htable_value(buf, count, ppos, &ima_htable.violations);
}

static const struct file_operations ima_htable_violations_ops = {
	.read = ima_show_htable_violations,
	.llseek = generic_file_llseek,
};

static ssize_t ima_show_measurements_count(struct file *filp,
					   char __user *buf,
					   size_t count, loff_t *ppos)
{
	return ima_show_htable_value(buf, count, ppos, &ima_htable.len);
}

static const struct file_operations ima_measurements_count_ops = {
	.read = ima_show_measurements_count,
	.llseek = generic_file_llseek,
};

#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
static struct dentry *digests_count;
static struct dentry *digest_list_data;

static int ima_upload_data(struct file *filp, loff_t size, char *buf);
static void ima_data_upload_result_stat(struct file *filp, int result);
static int ima_digest_list_data_release(struct file *filp);
u64 ima_digest_list_count_max;

static int __init digest_max_setup(char *str)
{
	u64 digest_list_max;

	if (!kstrtou64(str, 0, &digest_list_max))
		ima_digest_list_count_max = digest_list_max;

	return 1;
}
__setup("digest_list_max=", digest_max_setup);

#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
static struct dentry *digest_list_sig_enable_file;
static bool digest_list_sig_enable;

typedef struct {
	char *context;
	size_t size;
	size_t curlen;
} digest_buffer;
static digest_buffer digest_data_buf;
static digest_buffer digest_sig_buf;

static void clear_digest_buffer(digest_buffer *buf)
{
	if (buf) {
		kfree(buf->context);
		buf->context = NULL;
		buf->size = 0;
		buf->curlen = 0;
	}
}

struct digest_signature_hdr {
	u8 sig_info[5]; /* compatible with module signature head  */
	__be32 sig_len;
};
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */

#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */

/* returns pointer to hlist_node */
static void *ima_measurements_start(struct seq_file *m, loff_t *pos)
{
	loff_t l = *pos;
	struct ima_queue_entry *qe;

	/* we need a lock since pos could point beyond last element */
	rcu_read_lock();
	list_for_each_entry_rcu(qe, &ima_measurements, later) {
		if (!l--) {
			rcu_read_unlock();
			return qe;
		}
	}
	rcu_read_unlock();
	return NULL;
}

static void *ima_measurements_next(struct seq_file *m, void *v, loff_t *pos)
{
	struct ima_queue_entry *qe = v;

	/* lock protects when reading beyond last element
	 * against concurrent list-extension
	 */
	rcu_read_lock();
	qe = list_entry_rcu(qe->later.next, struct ima_queue_entry, later);
	rcu_read_unlock();
	(*pos)++;

	return (&qe->later == &ima_measurements) ? NULL : qe;
}

static void ima_measurements_stop(struct seq_file *m, void *v)
{
}

void ima_putc(struct seq_file *m, void *data, int datalen)
{
	while (datalen--)
		seq_putc(m, *(char *)data++);
}

/* print format:
 *       32bit-le=pcr#
 *       char[20]=template digest
 *       32bit-le=template name size
 *       char[n]=template name
 *       [eventdata length]
 *       eventdata[n]=template specific data
 */
int ima_measurements_show(struct seq_file *m, void *v)
{
	/* the list never shrinks, so we don't need a lock here */
	struct ima_queue_entry *qe = v;
	struct ima_template_entry *e;
	char *template_name;
	u32 pcr, namelen, template_data_len; /* temporary fields */
	bool is_ima_template = false;
	int i;

	/* get entry */
	e = qe->entry;
	if (e == NULL)
		return -1;

	template_name = (e->template_desc->name[0] != '\0') ?
	    e->template_desc->name : e->template_desc->fmt;

	/*
	 * 1st: PCRIndex
	 * PCR used defaults to the same (config option) in
	 * little-endian format, unless set in policy
	 */
	pcr = !ima_canonical_fmt ? e->pcr : cpu_to_le32(e->pcr);
	ima_putc(m, &pcr, sizeof(e->pcr));

	/* 2nd: template digest */
#ifdef CONFIG_RTOS_IMA_ENHANCEMENT
	ima_putc(m, e->digests[ima_hash_algo_idx].digest, TPM_DIGEST_SIZE_SHA2);
#else
	ima_putc(m, e->digests[ima_sha1_idx].digest, TPM_DIGEST_SIZE);
#endif
	/* 3rd: template name size */
	namelen = !ima_canonical_fmt ? strlen(template_name) :
		cpu_to_le32(strlen(template_name));
	ima_putc(m, &namelen, sizeof(namelen));

	/* 4th:  template name */
	ima_putc(m, template_name, strlen(template_name));

	/* 5th:  template length (except for 'ima' template) */
	if (strcmp(template_name, IMA_TEMPLATE_IMA_NAME) == 0)
		is_ima_template = true;

	if (!is_ima_template) {
		template_data_len = !ima_canonical_fmt ? e->template_data_len :
			cpu_to_le32(e->template_data_len);
		ima_putc(m, &template_data_len, sizeof(e->template_data_len));
	}

	/* 6th:  template specific data */
	for (i = 0; i < e->template_desc->num_fields; i++) {
		enum ima_show_type show = IMA_SHOW_BINARY;
		const struct ima_template_field *field =
			e->template_desc->fields[i];

		if (is_ima_template && strcmp(field->field_id, "d") == 0)
			show = IMA_SHOW_BINARY_NO_FIELD_LEN;
		if (is_ima_template && strcmp(field->field_id, "n") == 0)
			show = IMA_SHOW_BINARY_OLD_STRING_FMT;
		field->field_show(m, show, &e->template_data[i]);
	}
	return 0;
}

static const struct seq_operations ima_measurments_seqops = {
	.start = ima_measurements_start,
	.next = ima_measurements_next,
	.stop = ima_measurements_stop,
	.show = ima_measurements_show
};

static int ima_measurements_open(struct inode *inode, struct file *file)
{
	return seq_open(file, &ima_measurments_seqops);
}

static const struct file_operations ima_measurements_ops = {
	.open = ima_measurements_open,
	.read = seq_read,
	.llseek = seq_lseek,
	.release = seq_release,
};

void ima_print_digest(struct seq_file *m, u8 *digest, u32 size)
{
	u32 i;

	for (i = 0; i < size; i++)
		seq_printf(m, "%02x", *(digest + i));
}

/* print in ascii */
static int ima_ascii_measurements_show(struct seq_file *m, void *v)
{
	/* the list never shrinks, so we don't need a lock here */
	struct ima_queue_entry *qe = v;
	struct ima_template_entry *e;
	char *template_name;
	int i;

	/* get entry */
	e = qe->entry;
	if (e == NULL)
		return -1;

	template_name = (e->template_desc->name[0] != '\0') ?
	    e->template_desc->name : e->template_desc->fmt;

	/* 1st: PCR used (config option) */
	seq_printf(m, "%2d ", e->pcr);

	/* 2nd: SHA1 template hash */
#ifdef CONFIG_RTOS_IMA_DIGEST_SHA256
	if (m->file == NULL)
		return -1;
	if (strcmp(m->file->f_path.dentry->d_name.name,
			"ascii_runtime_measurements_sha256") == 0)
		ima_print_digest(m, e->digests[ima_hash_algo_idx].digest,
				TPM_DIGEST_SIZE_SHA2);
	else if (strcmp(m->file->f_path.dentry->d_name.name,
			"ascii_runtime_measurements") == 0)
		ima_print_digest(m, e->digests[ima_sha1_idx].digest,
				TPM_DIGEST_SIZE);
#else
	ima_print_digest(m, e->digests[ima_sha1_idx].digest, TPM_DIGEST_SIZE);
#endif
	/* 3th:  template name */
	seq_printf(m, " %s", template_name);

	/* 4th:  template specific data */
	for (i = 0; i < e->template_desc->num_fields; i++) {
		seq_puts(m, " ");
		if (e->template_data[i].len == 0)
			continue;

		e->template_desc->fields[i]->field_show(m, IMA_SHOW_ASCII,
							&e->template_data[i]);
	}
	seq_puts(m, "\n");
	return 0;
}

static const struct seq_operations ima_ascii_measurements_seqops = {
	.start = ima_measurements_start,
	.next = ima_measurements_next,
	.stop = ima_measurements_stop,
	.show = ima_ascii_measurements_show
};

static int ima_ascii_measurements_open(struct inode *inode, struct file *file)
{
	return seq_open(file, &ima_ascii_measurements_seqops);
}

static const struct file_operations ima_ascii_measurements_ops = {
	.open = ima_ascii_measurements_open,
	.read = seq_read,
	.llseek = seq_lseek,
	.release = seq_release,
};

static ssize_t ima_read_policy(char *path)
{
	void *data = NULL;
	char *datap;
	size_t size;
	int rc, pathlen = strlen(path);

	char *p;

	/* remove \n */
	datap = path;
	strsep(&datap, "\n");

	rc = kernel_read_file_from_path(path, 0, &data, INT_MAX, NULL,
					READING_POLICY);
	if (rc < 0) {
		pr_err("Unable to open file: %s (%d)", path, rc);
		return rc;
	}
	size = rc;
	rc = 0;

	datap = data;
	while (size > 0 && (p = strsep(&datap, "\n"))) {
		pr_debug("rule: %s\n", p);
		rc = ima_parse_add_rule(p);
		if (rc < 0)
			break;
		size -= rc;
	}

	vfree(data);
	if (rc < 0)
		return rc;
	else if (size)
		return -EINVAL;
	else
		return pathlen;
}

static ssize_t ima_write_policy(struct file *file, const char __user *buf,
				size_t datalen, loff_t *ppos)
{
	char *data;
	ssize_t result;

#ifdef CONFIG_RTOS_IMA_TPM_DECOUPLE
	ima_validate_tpm(file);
#endif /* CONFIG_RTOS_IMA_TPM_DECOUPLE */
#ifndef CONFIG_RTOS_CIV_DIGEST_LIST
	if (datalen >= PAGE_SIZE)
		datalen = PAGE_SIZE - 1;
#endif

	/* No partial writes. */
	result = -EINVAL;
	if (*ppos != 0)
		goto out;

	data = memdup_user_nul(buf, datalen);
	if (IS_ERR(data)) {
		result = PTR_ERR(data);
		goto out;
	}

#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	/* upload data to initialize the digest_list_data and policy */
	result = ima_upload_data(file, datalen, data);
#else
	result = mutex_lock_interruptible(&ima_write_mutex);
	if (result < 0)
		goto out_free;

	if (data[0] == '/') {
		result = ima_read_policy(data);
	} else if (ima_appraise & IMA_APPRAISE_POLICY) {
		pr_err("signed policy file (specified as an absolute pathname) required\n");
		integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
				    "policy_update", "signed policy required",
				    1, 0);
		result = -EACCES;
	} else {
		result = ima_parse_add_rule(data);
	}
	mutex_unlock(&ima_write_mutex);
out_free:
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */
	kfree(data);
out:
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	ima_data_upload_result_stat(file, result);
#else
	if (result < 0)
		valid_policy = 0;
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */
	return result;
}

static struct dentry *ima_dir;
static struct dentry *ima_symlink;
static struct dentry *binary_runtime_measurements;
#ifndef CONFIG_RTOS_IMA_ENHANCEMENT
static struct dentry *ascii_runtime_measurements;
#endif
static struct dentry *runtime_measurements_count;
static struct dentry *violations;
static struct dentry *ima_policy;
#ifdef CONFIG_RTOS_IMA_DIGEST_SHA256
static struct dentry *ascii_runtime_measurements_sha256;
#endif

enum ima_fs_flags {
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	IMA_POLICY_BUSY,
	IMA_DIGEST_LIST_DATA_BUSY,
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */
	IMA_FS_BUSY,
};

#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
static enum ima_fs_flags ima_get_dentry_flag(struct file *filp)
{
	struct dentry *dentry = file_dentry(filp);
	enum ima_fs_flags flag = IMA_FS_BUSY;

	if (dentry == ima_policy)
		flag = IMA_POLICY_BUSY;
	else if (dentry == digest_list_data)
		flag = IMA_DIGEST_LIST_DATA_BUSY;

	return flag;
}
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */

static unsigned long ima_fs_flags;

#ifdef	CONFIG_IMA_READ_POLICY
static const struct seq_operations ima_policy_seqops = {
		.start = ima_policy_start,
		.next = ima_policy_next,
		.stop = ima_policy_stop,
		.show = ima_policy_show,
};
#endif

/*
 * ima_open_policy: sequentialize access to the policy file
 */
static int ima_open_policy(struct inode *inode, struct file *filp)
{
	if (!(filp->f_flags & O_WRONLY)) {
#ifndef	CONFIG_IMA_READ_POLICY
		return -EACCES;
#else
		if ((filp->f_flags & O_ACCMODE) != O_RDONLY)
			return -EACCES;
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		return seq_open(filp, &ima_policy_seqops);
#endif
	}
#ifndef	CONFIG_RTOS_CIV_DIGEST_LIST
	if (test_and_set_bit(IMA_FS_BUSY, &ima_fs_flags))
		return -EBUSY;
#endif
	return 0;
}

#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
static int rtos_ima_open_policy(struct inode *inode, struct file *filp)
{
	enum ima_fs_flags flag = ima_get_dentry_flag(filp);
	int ret;
	struct dentry *dentry = file_dentry(filp);

	if (dentry == digest_list_data) {
		ret = mutex_lock_interruptible(&ima_write_mutex);
		if (ret < 0)
			return -EBUSY;
	}
	ret = ima_open_policy(inode, filp);
	if (ret < 0) {
		if (dentry == digest_list_data)
			mutex_unlock(&ima_write_mutex);
		return ret;
	}
	if ((filp->f_flags & O_WRONLY) && test_and_set_bit(flag, &ima_fs_flags)) {
		if (dentry == digest_list_data)
			mutex_unlock(&ima_write_mutex);
		return -EBUSY;
	}
	if (dentry == digest_list_data)
		ima_set_digest_list_data_opened(true);
	return ret;
}
#endif

#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
/*
 * ima_digest_verify_parse - parse digest-list when digest signature enables
 */
static void ima_digest_verify_parse(void)
{
	int rc = -EINVAL;
	int parser_num = 0;

	if (!digest_list_sig_enable)
		pr_warn_once("write digest_list_data without signature verification.\n");

	if (digest_sig_buf.context && digest_list_sig_enable) {
		rc = kernel_verify_cms_data(digest_data_buf.context,
					digest_data_buf.size,
					digest_sig_buf.context,
					digest_sig_buf.size);
		clear_digest_buffer(&digest_sig_buf);
	}

	/* After signature is not enabled or verified correctly, parse all digest data */
	if (rc == 0 || !digest_list_sig_enable)
		parser_num = ima_parse_compact_list(digest_data_buf.size, digest_data_buf.context);
	else
		pr_err("IMA: verify digest_list_data signature failed, errno: %d\n", rc);

	ima_set_digest_list_data_stat(parser_num > 0);

	clear_digest_buffer(&digest_data_buf);
}
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */

/*
 * ima_release_policy - start using the new measure policy rules.
 *
 * Initially, ima_measure points to the default policy rules, now
 * point to the new policy rules, and remove the securityfs policy file,
 * assuming a valid policy.
 */
static int ima_release_policy(struct inode *inode, struct file *file)
{
	const char *cause = valid_policy ? "completed" : "failed";
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	enum ima_fs_flags flag = ima_get_dentry_flag(file);
#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
	struct dentry *dentry = file_dentry(file);

	if (dentry == digest_list_data)
		ima_digest_verify_parse();
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */

	if (flag == IMA_DIGEST_LIST_DATA_BUSY) {
		mutex_unlock(&ima_write_mutex);
		if (ima_digest_list_data_release(file) == 0)
			return 0;
	}
#endif /* CONFIG_RTOS_CIV_DIGEST_LIST */

	if ((file->f_flags & O_ACCMODE) == O_RDONLY)
		return seq_release(inode, file);

	if (valid_policy && ima_check_policy() < 0) {
		cause = "failed";
		valid_policy = 0;
	}

	pr_info("policy update %s\n", cause);
	integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
			    "policy_update", cause, !valid_policy, 0);

	if (!valid_policy) {
		ima_delete_rules();
#ifdef CONFIG_RTOS_IMA_ENHANCEMENT
		ima_policy_count_inc = 0;
#endif
		valid_policy = 1;
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
		clear_bit(flag, &ima_fs_flags);
#else
		clear_bit(IMA_FS_BUSY, &ima_fs_flags);
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */
		return 0;
	}

	ima_update_policy();
#ifdef CONFIG_RTOS_IMA_ENHANCEMENT
	ima_policy_count += ima_policy_count_inc;
	ima_policy_count_inc = 0;
#endif
#if !defined(CONFIG_IMA_WRITE_POLICY) && !defined(CONFIG_IMA_READ_POLICY)
	securityfs_remove(ima_policy);
	ima_policy = NULL;
#elif defined(CONFIG_IMA_WRITE_POLICY)
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	clear_bit(flag, &ima_fs_flags);
#else
	clear_bit(IMA_FS_BUSY, &ima_fs_flags);
#endif /* CONFIG_RTOS_CIV_DIGEST_LIST */
#elif defined(CONFIG_IMA_READ_POLICY)
	inode->i_mode &= ~S_IWUSR;
#endif
	return 0;
}

static const struct file_operations ima_measure_policy_ops = {
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	.open = rtos_ima_open_policy,
#else
	.open = ima_open_policy,
#endif
	.write = ima_write_policy,
	.read = seq_read,
	.release = ima_release_policy,
	.llseek = generic_file_llseek,
};

#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
static ssize_t digest_list_sig_enable_control(struct file *filp,
		const char __user *buf, size_t datalen, loff_t *ppos)
{
	ssize_t result;
	int digest_sig;

	result = mutex_lock_interruptible(&digest_list_sig_enable_mutex);
	if (result < 0)
		return -EBUSY;

	if (*ppos != 0 || digest_list_sig_enable) {
		result = -EINVAL;
		goto out;
	}

	result = kstrtou32_from_user(buf, datalen, 10, &digest_sig);
	if (result < 0)
		goto out;

	if (digest_sig == 1) {
		pr_info("IMA: Enable digest list signature verification\n");
		result = (ssize_t)datalen;
		digest_list_sig_enable = true;
		goto out;
	}
	digest_list_sig_enable = false;
	result = -EINVAL;
out:
	mutex_unlock(&digest_list_sig_enable_mutex);
	return result;
}

static const struct file_operations digest_list_sig_enable_ops = {
	.write = digest_list_sig_enable_control,
	.llseek = generic_file_llseek,
};
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */

static ssize_t ima_show_digests_count(struct file *filp,
					char __user *buf,
					size_t count, loff_t *ppos)
{
	return ima_show_htable_value(buf, count, ppos, &ima_digests_htable.len);
}

static const struct file_operations ima_digests_count_ops = {
	.read = ima_show_digests_count,
	.llseek = generic_file_llseek,
};

static const struct file_operations ima_digest_list_ops = {
	.open = rtos_ima_open_policy,
	.write = ima_write_policy,
	.release = ima_release_policy,
	.llseek = generic_file_llseek,
};

#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
static int ima_store_digest_info(const char *buf, const loff_t size)
{
	struct compact_list_hdr *digest_head = NULL;
	struct digest_signature_hdr sig_head;
	/* remain buffer size to parse  */
	loff_t remain_data_size = size;
	size_t siglen;

	/* Parse digest head */
	if (!digest_data_buf.context) {
		if (remain_data_size < sizeof(struct compact_list_hdr))
			return -EINVAL;

		digest_head = (struct compact_list_hdr *)(buf);
		if (digest_head->datalen <= 0 || digest_head->datalen > MAX_DIGEST_LEN)
			return -EINVAL;

		digest_data_buf.context = kmalloc(digest_head->datalen +
						  sizeof(struct compact_list_hdr),
						  GFP_KERNEL);
		if (!digest_data_buf.context)
			return -ENOMEM;

		digest_data_buf.size = digest_head->datalen + sizeof(struct compact_list_hdr);
	}

	/* Parse digest data */
	if (digest_data_buf.size > digest_data_buf.curlen) {
		remain_data_size = digest_data_buf.size - digest_data_buf.curlen;
		remain_data_size = remain_data_size > size ? size : remain_data_size;
		memcpy(digest_data_buf.context + digest_data_buf.curlen, buf, remain_data_size);
		digest_data_buf.curlen += remain_data_size;
		remain_data_size = size - remain_data_size;
	}

	/* If signature is enable, continue parsing signature */

	if (!digest_list_sig_enable)
		return size;

	if (remain_data_size > 0 && digest_sig_buf.size == 0) {
		if (remain_data_size < sizeof(struct digest_signature_hdr))
			return -EINVAL;
		memcpy(&sig_head, buf + size - remain_data_size,
		       sizeof(struct digest_signature_hdr));
		siglen = be32_to_cpu(sig_head.sig_len);
		if (siglen <= 0 || siglen > MAX_DIGEST_SIG_LEN)
			return -EINVAL;
		digest_sig_buf.size = siglen;
		digest_sig_buf.context = kmalloc(siglen, GFP_KERNEL);
		if (!digest_sig_buf.context)
			return -ENOMEM;
		remain_data_size -= sizeof(struct digest_signature_hdr);
	}

	if (digest_sig_buf.context && remain_data_size > 0) {
		siglen = digest_sig_buf.size - digest_sig_buf.curlen;
		siglen = remain_data_size > siglen ? siglen : remain_data_size;
		memcpy(digest_sig_buf.context + digest_sig_buf.curlen,
		       buf + size - remain_data_size, siglen);
		digest_sig_buf.curlen += siglen;
	}

	return size;
}
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */

static int ima_upload_data(struct file *filp, loff_t size, char *buf)
{
	struct dentry *dentry = file_dentry(filp);
	int result;

	if (size < 0)
		return -EINVAL;

	if (dentry == ima_policy) {
		result = mutex_lock_interruptible(&ima_write_mutex);
		if (result < 0)
			return -EINVAL;
		if (buf[0] == '/')
			result = ima_read_policy(buf);
		else
			result = ima_parse_add_rule(buf);
		mutex_unlock(&ima_write_mutex);
	} else if (dentry == digest_list_data) {
#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
		result = ima_store_digest_info(buf, size);
#else
		result = ima_parse_compact_list(size, buf);
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */
	} else {
		pr_err("Unknown data type\n");
		result = -EINVAL;
	}
	return result;
}

static void ima_data_upload_result_stat(struct file *filp, int result)
{
	struct dentry *dentry = file_dentry(filp);

	if (dentry == ima_policy && result < 0)
		valid_policy = 0;
	else if (dentry == digest_list_data && result < 0)
		ima_set_digest_list_data_stat(false);
}

static int ima_digest_list_data_release(struct file *filp)
{
	enum ima_fs_flags flag = ima_get_dentry_flag(filp);
	const char *cause = ima_get_digest_list_data_stat() &&
				ima_digest_list_upload_stat() ? "completed" :
				"failed";

	pr_info("IMA: digest list update %s\n", cause);
	integrity_audit_msg(AUDIT_INTEGRITY_STATUS, NULL, NULL,
			"digest_list_data_update", cause,
			!ima_get_digest_list_data_stat(), 0);

	ima_set_digest_list_data_opened(false);
	if (!ima_get_digest_list_data_stat()) {
		ima_set_digest_list_data_stat(true);
		clear_bit(flag, &ima_fs_flags);
	} else {
#ifndef CONFIG_IMA_WRITE_POLICY
		securityfs_remove(digest_list_data);
		digest_list_data = NULL;
#else
		clear_bit(flag, &ima_fs_flags);
#endif
	}
	return 0;
}

int ima_digest_list_add_securityfs(void)
{
	digests_count = securityfs_create_file("digests_count",
						S_IRUSR | S_IRGRP, ima_dir,
						NULL, &ima_digests_count_ops);
	if (IS_ERR(digests_count))
		goto out;

	digest_list_data = securityfs_create_file("digest_list_data", S_IWUSR,
						ima_dir, NULL,
						&ima_digest_list_ops);
	if (IS_ERR(digest_list_data))
		goto out;

#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
	digest_list_sig_enable_file =
		securityfs_create_file("digest_list_sig_enable_file",
				S_IWUSR, ima_dir, NULL,
				&digest_list_sig_enable_ops);
	if (IS_ERR(digest_list_sig_enable_file))
		goto out;
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */
	return 0;
out:
	return -1;
}

void ima_digest_list_del_securityfs(void)
{
	securityfs_remove(digests_count);
	securityfs_remove(digest_list_data);
#ifdef CONFIG_RTOS_IMA_DIGEST_SIG
	securityfs_remove(digest_list_sig_enable_file);
#endif /* CONFIG_RTOS_IMA_DIGEST_SIG */
}
#endif /* CONFIG_RTOS_CIV_DIGEST_LIST */

int __init ima_fs_init(void)
{
	ima_dir = securityfs_create_dir("ima", integrity_dir);
	if (IS_ERR(ima_dir))
		return -1;

	ima_symlink = securityfs_create_symlink("ima", NULL, "integrity/ima",
						NULL);
	if (IS_ERR(ima_symlink))
		goto out;

	binary_runtime_measurements =
	    securityfs_create_file("binary_runtime_measurements",
				   S_IRUSR | S_IRGRP, ima_dir, NULL,
				   &ima_measurements_ops);
	if (IS_ERR(binary_runtime_measurements))
		goto out;

#ifdef CONFIG_RTOS_IMA_DIGEST_SHA256
	ascii_runtime_measurements_sha256 =
	    securityfs_create_file("ascii_runtime_measurements_sha256",
			S_IRUSR | S_IRGRP, ima_dir, NULL,
			&ima_ascii_measurements_ops);
	if (IS_ERR(ascii_runtime_measurements_sha256))
		goto out;
#endif

#ifndef CONFIG_RTOS_IMA_ENHANCEMENT
	ascii_runtime_measurements =
	    securityfs_create_file("ascii_runtime_measurements",
				   S_IRUSR | S_IRGRP, ima_dir, NULL,
				   &ima_ascii_measurements_ops);
	if (IS_ERR(ascii_runtime_measurements))
		goto out;
#endif

	runtime_measurements_count =
	    securityfs_create_file("runtime_measurements_count",
				   S_IRUSR | S_IRGRP, ima_dir, NULL,
				   &ima_measurements_count_ops);
	if (IS_ERR(runtime_measurements_count))
		goto out;

	violations =
	    securityfs_create_file("violations", S_IRUSR | S_IRGRP,
				   ima_dir, NULL, &ima_htable_violations_ops);
	if (IS_ERR(violations))
		goto out;

	ima_policy = securityfs_create_file("policy", POLICY_FILE_FLAGS,
					    ima_dir, NULL,
					    &ima_measure_policy_ops);
	if (IS_ERR(ima_policy))
		goto out;
#ifdef CONFIG_RTOS_IMA_MEASURE_THRESHOLD
	ima_measurement_threshold =
		securityfs_create_file("ima_measurement_threshold",
					S_IWUSR, ima_dir, NULL,
					&ima_measurement_threshold_ops);
	if (IS_ERR(ima_measurement_threshold))
		goto out;
#endif
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	if (ima_digest_list_add_securityfs() == -1)
		goto out;
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */
#ifdef CONFIG_RTOS_IMA_APPRAISE_FAILLOG
	ima_appraise_faillog = securityfs_create_file("appraise_faillog", 0600,
						      ima_dir, NULL, &ima_appraise_faillog_ops);
	if (IS_ERR(ima_appraise_faillog))
		goto out;
#endif
	return 0;
out:
	securityfs_remove(ima_policy);
#ifdef CONFIG_RTOS_IMA_DIGEST_SHA256
	securityfs_remove(ascii_runtime_measurements_sha256);
#endif
#ifdef CONFIG_RTOS_IMA_MEASURE_THRESHOLD
	securityfs_remove(ima_measurement_threshold);
#endif
#ifdef CONFIG_RTOS_CIV_DIGEST_LIST
	ima_digest_list_del_securityfs();
#endif  /* CONFIG_RTOS_CIV_DIGEST_LIST */
#ifdef CONFIG_RTOS_IMA_APPRAISE_FAILLOG
	securityfs_remove(ima_appraise_faillog);
#endif
	securityfs_remove(violations);
	securityfs_remove(runtime_measurements_count);
#ifndef CONFIG_RTOS_IMA_ENHANCEMENT
	securityfs_remove(ascii_runtime_measurements);
#endif
	securityfs_remove(binary_runtime_measurements);
	securityfs_remove(ima_symlink);
	securityfs_remove(ima_dir);
	return -1;
}

#ifdef CONFIG_RTOS_IMA_TPM_DECOUPLE
bool dentry_is_ima_policy(struct dentry *dentry)
{
	return dentry == ima_policy ? true : false;
}
#endif
